﻿using BCCommon;
using BCCommon.Extensions;
using BCCommon.OAEnums;
using BCCommon.OAEnums.WorkflowActive;
using BCData.OA.WorkflowActive.WorkflowActivityStepCompleteChecking;
using BCData.OA.WorkflowActive.WorkflowActivityStepFormConfig;
using BCData.OA.WorkflowActive.WorkflowActivityStepFormItem;
using BCData.OA.WorkflowActive.WorkflowActivityStepReviewer;
using BCData.OA.WorkflowActivity.WorkflowActivity;
using BCData.OA.WorkflowActivity.WorkflowActivityStep;
using BCData.OA.WorkflowActivity.WorkflowActivityStepSpecificFormItem;
using BCData.OA.WorkflowTemplate.WorkflowCategory;
using BCData.OA.WorkflowTemplate.WorkflowTemplate;
using BCData.OA.WorkflowTemplate.WorkflowTemplateStep;
using BCData.OA.WorkflowTemplate.WorkflowTemplateStepBaseConfig;
using BCData.OA.WorkflowTemplate.WorkflowTemplateStepButtonConfig;
using BCData.OA.WorkflowTemplate.WorkflowTemplateStepFormConfig;
using BCData.OA.WorkflowTemplate.WorkflowTemplateStepFormTemplateConfig;
using BCData.OA.WorkflowTemplate.WorkflowTemplateStepLineConfig;
using BCData.OA.WorkflowTemplate.WorkflowTemplateStepReviewerConfig;
using BCData.OA.WorkflowTemplate.WorkflowTemplateStepStartBaseConfig;
using BCData.Sim.Admin.Admin;
using BCData.Sim.Admin.StaffOrganizationMappingRecord;
using BCData.Sim.Company.Position;
using BCDto.OA.WorkflowActive.WorkflowActive;
using BCDto.OA.WorkflowActive.WorkflowActivity;
using BCDto.OA.WorkflowActive.WorkflowActivityOperation;
using BCDto.OA.WorkflowActive.WorkflowActivityStep;
using BCDto.OA.WorkflowActive.WorkflowActivityStepFormConfig;
using BCDto.OA.WorkflowActive.WorkflowActivityStepFormItem;
using BCDto.OA.WorkflowActive.WorkflowActivityStepSpecificFormItem;
using BCDto.OA.WorkflowTemplate.WorkflowTemplate;
using BCDto.OA.WorkflowTemplate.WorkflowTemplateStep;
using BCDto.OA.WorkflowTemplate.WorkflowTemplateStepButtonConfig;
using BCDto.Sim.Admin.Admin;
using BCDto.Website.User;
using BCEntity.OA.WorkflowActive.WorkflowActivity;
using BCEntity.OA.WorkflowActive.WorkflowActivityStep;
using BCEntity.OA.WorkflowActive.WorkflowActivityStepCompleteChecking;
using BCEntity.OA.WorkflowActive.WorkflowActivityStepFormConfig;
using BCEntity.OA.WorkflowActive.WorkflowActivityStepFormItem;
using BCEntity.OA.WorkflowActive.WorkflowActivityStepReviewer;
using BCEntity.OA.WorkflowActive.WorkflowActivityStepSpecificFormItem;
using BCEntity.OA.WorkflowTemplate.WorkflowTemplateStep;
using BCEntity.OA.WorkflowTemplate.WorkflowTemplateStepLineConfig;
using BCWorkflowEngine.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCWorkflowEngine
{
    public class WorkflowEngine : IWorkflowEngine
    {
        private readonly IDatabaseContext databaseContext;
        private readonly IAdminData adminData;
        private readonly IPositionData positionData;
        private readonly IStaffOrganizationMappingRecordData staffOrganizationMappingRecordData;
        private readonly IWorkflowCategoryData workflowCategoryData;
        private readonly IWorkflowTemplateData workflowTemplateData;
        private readonly IWorkflowTemplateStepData workflowTemplateStepData;
        private readonly IWorkflowTemplateStepReviewerConfigData workflowTemplateStepReviewerConfigData;
        private readonly IWorkflowTemplateStepStartBaseConfigData workflowTemplateStepStartBaseConfigData;
        private readonly IWorkflowTemplateStepBaseConfigData workflowTemplateStepBaseConfigData;
        private readonly IWorkflowTemplateStepFormTemplateConfigData workflowTemplateStepFormTemplateConfigData;
        private readonly IWorkflowTemplateStepFormConfigData workflowTemplateStepFormConfigData;
        private readonly IWorkflowTemplateStepButtonConfigData workflowTemplateStepButtonConfigData;
        private readonly IWorkflowTemplateStepLineConfigData workflowTemplateStepLineConfigData;
        private readonly IWorkflowActivityData workflowActivityData;
        private readonly IWorkflowActivityStepData workflowActivityStepData;
        private readonly IWorkflowActivityStepReviewerData workflowActivityStepReviewerData;
        private readonly IWorkflowActivityStepCompleteCheckingData workflowActivityStepCompleteCheckingData;
        private readonly IWorkflowActivityStepFormConfigData workflowActivityStepFormConfigData;
        private readonly IWorkflowActivityStepFormItemData workflowActivityStepFormItemData;
        private readonly IWorkflowActivityStepSpecificFormItemData workflowActivityStepSpecificFormItemData;
        public WorkflowEngine(IDatabaseContext databaseContext,
            IAdminData adminData,
            IPositionData positionData,
            IStaffOrganizationMappingRecordData staffOrganizationMappingRecordData,
            IWorkflowCategoryData workflowCategoryData,
            IWorkflowTemplateData workflowTemplateData,
            IWorkflowTemplateStepData workflowTemplateStepData,
            IWorkflowTemplateStepReviewerConfigData workflowTemplateStepReviewerConfigData,
            IWorkflowTemplateStepStartBaseConfigData workflowTemplateStepStartBaseConfigData,
            IWorkflowTemplateStepBaseConfigData workflowTemplateStepBaseConfigData,
            IWorkflowTemplateStepFormTemplateConfigData workflowTemplateStepFormTemplateConfigData,
            IWorkflowTemplateStepFormConfigData workflowTemplateStepFormConfigData,
            IWorkflowTemplateStepButtonConfigData workflowTemplateStepButtonConfigData,
            IWorkflowTemplateStepLineConfigData workflowTemplateStepLineConfigData,
            IWorkflowActivityData workflowActivityData,
            IWorkflowActivityStepData workflowActivityStepData,
            IWorkflowActivityStepReviewerData workflowActivityStepReviewerData,
            IWorkflowActivityStepCompleteCheckingData workflowActivityStepCompleteCheckingData,
            IWorkflowActivityStepFormConfigData workflowActivityStepFormConfigData,
            IWorkflowActivityStepFormItemData workflowActivityStepFormItemData,
            IWorkflowActivityStepSpecificFormItemData workflowActivityStepSpecificFormItemData)
        {
            this.databaseContext = databaseContext;
            this.adminData = adminData;
            this.positionData = positionData;
            this.staffOrganizationMappingRecordData = staffOrganizationMappingRecordData;
            this.workflowCategoryData = workflowCategoryData;
            this.workflowTemplateData = workflowTemplateData;
            this.workflowTemplateStepData = workflowTemplateStepData;
            this.workflowTemplateStepReviewerConfigData = workflowTemplateStepReviewerConfigData;
            this.workflowTemplateStepStartBaseConfigData = workflowTemplateStepStartBaseConfigData;
            this.workflowTemplateStepBaseConfigData = workflowTemplateStepBaseConfigData;
            this.workflowTemplateStepFormTemplateConfigData = workflowTemplateStepFormTemplateConfigData;
            this.workflowTemplateStepFormConfigData = workflowTemplateStepFormConfigData;
            this.workflowTemplateStepButtonConfigData = workflowTemplateStepButtonConfigData;
            this.workflowTemplateStepLineConfigData = workflowTemplateStepLineConfigData;
            this.workflowActivityData = workflowActivityData;
            this.workflowActivityStepData = workflowActivityStepData;
            this.workflowActivityStepReviewerData = workflowActivityStepReviewerData;
            this.workflowActivityStepCompleteCheckingData = workflowActivityStepCompleteCheckingData;
            this.workflowActivityStepFormConfigData = workflowActivityStepFormConfigData;
            this.workflowActivityStepFormItemData = workflowActivityStepFormItemData;
            this.workflowActivityStepSpecificFormItemData = workflowActivityStepSpecificFormItemData;
        }

        #region 初始化工作流活动实例
        public WorkflowActivityEntity InitWorkflowActivityInstance(WorkflowTemplateDto workflowTemplateDto, AdminDto adminDto, UserDto userDto)
        {
            #region 信息验证
            if (workflowTemplateDto == null)
            {
                throw new ArgumentException("工作流模板信息不应为空!");
            }
            if (workflowTemplateDto.CategoryCode == null)
            {
                throw new ArgumentException("缺少工作流分类编码!");
            }
            if (workflowTemplateDto.FlowDesign == null)
            {
                throw new ArgumentException("工作流设计信息不应为在!");
            }
            if (!workflowTemplateDto.FlowDesign.FlowObjs.Any())
            {
                throw new ArgumentException("工作流步骤列表不应为空!");
            }
            if (!workflowTemplateDto.FlowDesign.FlowObjs.Any(p => p.Step == 0))
            {
                throw new ArgumentException("工作流第0步步骤不存在!");
            }
            #endregion
            var categoryEntity = this.workflowCategoryData.GetEntity(workflowTemplateDto.CategoryCode).GetAwaiter().GetResult();
            if (categoryEntity == null)
            {
                throw new ArgumentException("工作流分类不存在!");
            }

            WorkflowActivityEntity entity = new WorkflowActivityEntity();
            entity.WorkflowCategoryId = categoryEntity.WorkflowCategoryId;
            entity.CategoryCode = workflowTemplateDto.CategoryCode;
            entity.CategoryName = workflowTemplateDto.CategoryName;
            entity.TemplateCode = workflowTemplateDto.TemplateCode;
            entity.TemplateName = workflowTemplateDto.TemplateName;
            entity.TemplateIcon = workflowTemplateDto.TemplateIcon;
            entity.TemplateDescription = workflowTemplateDto.TemplateDescription;
            entity.WorkflowCode = Guid.NewGuid().ToString();
            entity.WorkflowName = workflowTemplateDto.TemplateName;
            entity.IsBaseWorkflow = workflowTemplateDto.IsBaseFlow;
            if (adminDto != null)
            {
                entity.CompanyId = adminDto.CompanyId;
                entity.DepartmentId = adminDto.DepartmentId;
                entity.AdminId = adminDto.AdminId;
                entity.AuthorFullName = adminDto.FullName;
                entity.RoleType = OAAuthorRoleType.Admin;
                entity.CreateAdminId = adminDto.AdminId;
                entity.CreateAdminName = adminDto.FullName;
            }
            else
            {
                entity.OtherUserId = userDto.UserId;
                entity.AuthorFullName = userDto.UserName;
                entity.RoleType = OAAuthorRoleType.Other;
                entity.CreateAdminId = userDto.UserId;
                entity.CreateAdminName = userDto.UserName;
            }
            entity.ActivityStatus = OAActivityStatus.Ready;

            WorkflowTemplateStepDto stepDto = workflowTemplateDto.FlowDesign.FlowObjs.Single(p => p.Step == 0);
            var startBaseConfigEntity = this.workflowTemplateStepStartBaseConfigData.GetEntity(stepDto.Id).GetAwaiter().GetResult();
            WorkflowActivityStepEntity stepEntity = new WorkflowActivityStepEntity();
            stepEntity.TemplateCode = stepDto.TemplateCode;
            stepEntity.TemplateName = stepDto.TemplateName;
            stepEntity.WorkflowCode = entity.WorkflowCode;
            stepEntity.WorkflowName = entity.WorkflowName;
            stepEntity.TemplateStepCode = stepDto.Id;
            stepEntity.StepCode = Guid.NewGuid().ToString();
            stepEntity.NodeName = stepDto.NodeName;
            stepEntity.NodeType = stepDto.NodeType;
            stepEntity.StepType = OAActivityStepType.Created;
            stepEntity.Step = stepDto.Step;
            stepEntity.StepStatus = OAActivityStepStatus.Active;
            stepEntity.StepOrder = 0;
            stepEntity.IsAdditionalValidationStep = false;
            stepEntity.ActiveTime = DateTime.Now;
            stepEntity.AllowAssignNextValidater = startBaseConfigEntity.NextValidater == "AllowAssign";
            if (adminDto != null)
            {
                stepEntity.ExecutorId = adminDto.AdminId;
                stepEntity.ExecutorName = adminDto.FullName;
                stepEntity.ExecutorType = OAAuthorRoleType.Admin;
            }
            else
            {
                stepEntity.ExecutorId = userDto.UserId;
                stepEntity.ExecutorName = userDto.UserName;
                stepEntity.ExecutorType = OAAuthorRoleType.Other;
            }

            List<WorkflowActivityStepCompleteCheckingEntity> completeCheckingEntities = GetStepCompleteCheckingList(stepDto.Id, stepEntity);

            this.databaseContext.BeginTransaction();
            var entityResult = this.workflowActivityData.Add(entity).GetAwaiter().GetResult();
            if (entityResult == null)
            {
                throw new ArgumentException("初始化工作流活动失败!");
            }
            stepEntity.WorkflowActivityId = entityResult.WorkflowActivityId;
            var stepEntityResult = this.workflowActivityStepData.Add(stepEntity).GetAwaiter().GetResult();
            if (stepEntityResult == null)
            {
                throw new ArgumentException("初始化工作流活动步骤失败!");
            }
            if (completeCheckingEntities.Any())
            {
                foreach (var item in completeCheckingEntities)
                {
                    item.WorkflowActivityId = entityResult.WorkflowActivityId;
                    item.WorkflowActivityStepId = stepEntityResult.WorkflowActivityStepId;
                    item.CreateTime = DateTime.Now;
                    item.OpertionStatus = OAActivityStepOpertionStatus.Pending;
                }

                if (!this.workflowActivityStepCompleteCheckingData.Add(completeCheckingEntities).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("构建工作流步骤操作检查列表失败!");
                }
            }
            databaseContext.Commit();
            return entityResult;
        }
        #endregion

        #region 提交工作流步骤表单
        public List<WorkflowActivityStepFormConfigDto> SubmitWorkflowActivityStepForm(List<WorkflowActivityStepFormConfigRequestDto> formConfigRequestDtos, AdminDto adminDto, UserDto userDto)
        {
            List<WorkflowActivityStepFormConfigEntity> formConfigEntities = new List<WorkflowActivityStepFormConfigEntity>();
            List<WorkflowActivityStepFormItemEntity> formItemEntities = new List<WorkflowActivityStepFormItemEntity>();
            List<WorkflowActivityStepSpecificFormItemEntity> specificFormItemEntities = new List<WorkflowActivityStepSpecificFormItemEntity>();
            Dictionary<string, WorkflowActivityStepEntity> formConfigDic = new Dictionary<string, WorkflowActivityStepEntity>();
            foreach (var item in formConfigRequestDtos)
            {
                var templateFormConfigEntity = this.workflowTemplateStepFormConfigData.GetEntity(item.FormConfigCode).GetAwaiter().GetResult();
                if (templateFormConfigEntity == null)
                {
                    throw new ArgumentException("模板表单配置码不存在!");
                }
                var activityEntity = this.workflowActivityData.GetEntity(item.WorkflowActivityId).GetAwaiter().GetResult();
                if (activityEntity == null)
                {
                    throw new ArgumentException("工作流活动不存在!");
                }
                if ((!item.WorkflowActivityStepId.HasValue || item.WorkflowActivityStepId.Value == 0) && this.workflowActivityStepData.GetActivityStepMoreThanOne(item.WorkflowActivityId).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("此表单步骤流程存在多个活动步骤，步骤Id不允许为空!");
                }
                var activityStepEntity = !item.WorkflowActivityStepId.HasValue || item.WorkflowActivityStepId.Value == 0
                    ? this.workflowActivityStepData.GetActivityEntity(item.WorkflowActivityId).GetAwaiter().GetResult()
                    : this.workflowActivityStepData.GetActivityEntity(item.WorkflowActivityStepId.Value).GetAwaiter().GetResult();
                if (activityStepEntity == null)
                {
                    throw new ArgumentException("此工作流活动正在进行中步骤不存在!");
                }
                var formConfigEntity = item.As<WorkflowActivityStepFormConfigEntity>();
                formConfigEntity.TemplateCode = activityEntity.TemplateCode;
                formConfigEntity.TemplateName = activityEntity.TemplateName;
                formConfigEntity.WorkflowCode = activityEntity.WorkflowCode;
                formConfigEntity.WorkflowName = activityEntity.WorkflowName;
                formConfigEntity.StepCode = activityStepEntity.StepCode;
                formConfigEntity.FormCategoryCode = templateFormConfigEntity.FormCategoryCode;
                formConfigEntity.FormCategoryName = templateFormConfigEntity.FormCategoryName;
                formConfigEntity.CreateAdminId = adminDto != null ? adminDto.AdminId : userDto.UserId;
                formConfigEntity.CreateAdminName = adminDto != null ? adminDto.FullName : userDto.UserName;
                formConfigEntity.SubmitRole = adminDto != null ? "Admin" : "Other";
                formConfigEntities.Add(formConfigEntity);
                formConfigDic.Add(formConfigEntity.FormConfigCode, activityStepEntity);
                int i = 0;
                if (formConfigEntity.IsSpecificForm)
                {
                    foreach (var formItem in item.SpecificFormItemActivity)
                    {
                        var formItemEntity = formItem.As<WorkflowActivityStepSpecificFormItemEntity>();
                        formItemEntity.WorkflowActivityId = activityEntity.WorkflowActivityId;
                        formItemEntity.TemplateCode = activityEntity.TemplateCode;
                        formItemEntity.TemplateName = activityEntity.TemplateName;
                        formItemEntity.WorkflowCode = activityEntity.WorkflowCode;
                        formItemEntity.WorkflowName = activityEntity.WorkflowName;
                        formItemEntity.StepCode = activityStepEntity.StepCode;
                        formItemEntity.CreateAdminId = adminDto != null ? adminDto.AdminId : userDto.UserId;
                        formItemEntity.CreateAdminName = adminDto != null ? adminDto.FullName : userDto.UserName;
                        formItemEntity.SubmitRole = adminDto != null ? "Admin" : "Other";
                        specificFormItemEntities.Add(formItemEntity);
                        i++;
                    }
                }
                else
                {
                    foreach (var formItem in item.FormItemActivity)
                    {
                        var formItemEntity = formItem.As<WorkflowActivityStepFormItemEntity>();
                        formItemEntity.WorkflowActivityId = activityEntity.WorkflowActivityId;
                        formItemEntity.TemplateCode = activityEntity.TemplateCode;
                        formItemEntity.TemplateName = activityEntity.TemplateName;
                        formItemEntity.WorkflowCode = activityEntity.WorkflowCode;
                        formItemEntity.WorkflowName = activityEntity.WorkflowName;
                        formItemEntity.StepCode = activityStepEntity.StepCode;
                        formItemEntity.ItemOrder = i;
                        formItemEntity.CreateAdminId = adminDto != null ? adminDto.AdminId : userDto.UserId;
                        formItemEntity.CreateAdminName = adminDto != null ? adminDto.FullName : userDto.UserName;
                        formItemEntity.SubmitRole = adminDto != null ? "Admin" : "Other";
                        formItemEntities.Add(formItemEntity);
                        i++;
                    }
                }
            }

            List<WorkflowActivityStepFormConfigDto> result = new List<WorkflowActivityStepFormConfigDto>();

            this.databaseContext.BeginTransaction();
            foreach (var item in formConfigEntities)
            {
                var formConfigResult = this.workflowActivityStepFormConfigData.Add(item).GetAwaiter().GetResult();
                if (formConfigResult == null)
                {
                    throw new ArgumentException("提交表单失败!");
                }
                var formConfigResultDto = formConfigResult.As<WorkflowActivityStepFormConfigDto>();
                if (!item.IsSpecificForm)
                {
                    formConfigResultDto.FormItemActivity = new List<WorkflowActivityStepFormItemDto>();
                    foreach (var formItem in formItemEntities.Where(p => p.FormConfigCode == item.FormConfigCode))
                    {
                        formItem.WorkflowActivityStepFormConfigId = formConfigResult.WorkflowActivityStepFormConfigId;
                        var formItemResult = this.workflowActivityStepFormItemData.Add(formItem).GetAwaiter().GetResult();
                        if (formItemResult == null)
                        {
                            throw new ArgumentException("保存表单内容时意外失败!");
                        }
                        formConfigResultDto.FormItemActivity.Add(formItemResult.As<WorkflowActivityStepFormItemDto>());
                    }
                }
                else
                {
                    formConfigResultDto.SpecificFormItemActivity = new List<WorkflowActivityStepSpecificFormItemDto>();
                    foreach (var formItem in specificFormItemEntities.Where(p => p.FormConfigCode == item.FormConfigCode))
                    {
                        formItem.WorkflowActivityStepFormConfigId = formConfigResult.WorkflowActivityStepFormConfigId;
                        var formItemResult = this.workflowActivityStepSpecificFormItemData.Add(formItem).GetAwaiter().GetResult();
                        if (formItemResult == null)
                        {
                            throw new ArgumentException("保存表单内容时意外失败!");
                        }
                        formConfigResultDto.SpecificFormItemActivity.Add(formItemResult.As<WorkflowActivityStepSpecificFormItemDto>());
                    }
                }
                WorkflowActivityStepCompleteCheckingEntity completeCheckingEntity = new WorkflowActivityStepCompleteCheckingEntity()
                {
                    WorkflowActivityStepId = formConfigDic[item.FormConfigCode].WorkflowActivityStepId,
                    FormConfigCode = item.FormConfigCode,
                    OpertionStatus = OAActivityStepOpertionStatus.Done
                };

                if (!this.workflowActivityStepCompleteCheckingData.UpdateStatusForFormSubmit(completeCheckingEntity).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("修改任务表单提交检查完成时失败!");
                }
                result.Add(formConfigResultDto);
            }
            this.databaseContext.Commit();
            return result;
        }
        #endregion

        #region 工作流活动步骤操作
        public WorkflowActivityDto Execution(WorkflowActivityOperationRequestDto workflowActivityOperationRequestDto)
        {
            if ((!workflowActivityOperationRequestDto.WorkflowActivityStepId.HasValue || workflowActivityOperationRequestDto.WorkflowActivityStepId.Value == 0) && this.workflowActivityStepData.GetActivityStepMoreThanOne(workflowActivityOperationRequestDto.WorkflowActivityId).GetAwaiter().GetResult())
            {
                throw new ArgumentException("此表单步骤流程存在多个活动步骤，步骤Id不允许为空!");
            }
            var activityStepEntity = !workflowActivityOperationRequestDto.WorkflowActivityStepId.HasValue || workflowActivityOperationRequestDto.WorkflowActivityStepId.Value == 0
                ? this.workflowActivityStepData.GetActivityEntity(workflowActivityOperationRequestDto.WorkflowActivityId).GetAwaiter().GetResult()
                : this.workflowActivityStepData.GetEntity(workflowActivityOperationRequestDto.WorkflowActivityStepId.Value).GetAwaiter().GetResult();
            if (activityStepEntity.StepStatus == OAActivityStepStatus.Pending)
            {
                throw new ArgumentException("此步骤尚未开始!");
            }
            if (activityStepEntity.StepStatus == OAActivityStepStatus.Done)
            {
                throw new ArgumentException("此步骤已经结束!");
            }
            CheckCurrentlyStepOpertionComplete(activityStepEntity);

            databaseContext.BeginTransaction();

            if (workflowActivityOperationRequestDto.StepCompleteType == OAActivityStepCompleteType.Pass)
            {
                WorkflowActivityStepEntity stepEntity = PassNode(activityStepEntity);
                if (workflowActivityOperationRequestDto.NextAuditorId.HasValue)
                {
                    SetNextNode(stepEntity, workflowActivityOperationRequestDto.NextAuditorId.Value, workflowActivityOperationRequestDto.Remark);
                }
                else
                {
                    GetTargetStepInfo(stepEntity, true);

                    //var templateStepList = this.workflowTemplateStepData.GetList(activityStepEntity.TemplateCode).GetAwaiter().GetResult();
                    //int nextStep = stepEntity.Step + 1;
                    //var nextStepList = templateStepList.Where(p => p.Step == nextStep);

                    //foreach (var templateStepEntity in nextStepList)
                    //{
                    //    var stepBaseCofnigEntity = this.workflowTemplateStepBaseConfigData.GetEntity(templateStepEntity.Id).GetAwaiter().GetResult();
                    //    if (stepBaseCofnigEntity != null)
                    //    {
                    //        SetNextNode(templateStepEntity, stepEntity, OAActivityStepType.Created, stepBaseCofnigEntity.AllowAdditionalValidationPerson);
                    //    }
                    //    else
                    //    {
                    //        SetNextNode(templateStepEntity, stepEntity, OAActivityStepType.Created, false);
                    //    }
                    //}
                }
                var workflowActivityEntity = this.workflowActivityData.GetEntity(activityStepEntity.WorkflowActivityId).GetAwaiter().GetResult();
                if (activityStepEntity.Step == 0 && workflowActivityEntity.ActivityStatus == OAActivityStatus.Ready)
                {
                    workflowActivityEntity.ActivityStatus = OAActivityStatus.Ongoing;
                    var workflowActivityResult = this.workflowActivityData.Update(workflowActivityEntity).GetAwaiter().GetResult();
                    if (workflowActivityResult == null)
                    {
                        throw new ArgumentException("修改任务状态至进行中时失败!");
                    }
                }
            }
            else
            {
                WorkflowActivityStepEntity stepEntity = RejectNode(activityStepEntity);
                var workflowActivityEntity = this.workflowActivityData.GetEntity(activityStepEntity.WorkflowActivityId).GetAwaiter().GetResult();
                if (!workflowActivityEntity.IsBaseWorkflow)
                {
                    bool isClosed = false;
                    var activityStepList = this.workflowActivityStepData.GetList(activityStepEntity.WorkflowActivityId).Result.OrderByDescending(p => p.WorkflowActivityStepId);
                    if (activityStepList.Any())
                    {
                        int i = 1;
                        var tempStepEntity = activityStepList.Skip(i).Take(1).FirstOrDefault();
                        while (tempStepEntity != null)
                        {
                            if (tempStepEntity.NodeType == OAStepNodeType.Start)
                            {
                                this.workflowActivityData.UpdateClosed(activityStepEntity.WorkflowActivityId, OAActivityStatus.Closed, workflowActivityOperationRequestDto.Remark).GetAwaiter().GetResult();
                                isClosed = true;
                                break;
                            }
                            else if (tempStepEntity.NodeType == OAStepNodeType.Condition)
                            {
                                i += 1;
                                tempStepEntity = activityStepList.Skip(i).Take(1).FirstOrDefault();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    if (!isClosed)
                    {
                        if (stepEntity.NodeType == OAStepNodeType.Condition)
                        {
                            GetTargetStepInfo(stepEntity, true);
                        }
                        else
                        {
                            SetRejectNode(stepEntity, workflowActivityOperationRequestDto.Remark, false);
                        }
                    }
                }
                else
                {
                    if (stepEntity.NodeType == OAStepNodeType.Condition)
                    {
                        GetTargetStepInfo(stepEntity, true);
                    }
                    else
                    {
                        SetRejectNode(stepEntity, workflowActivityOperationRequestDto.Remark, false);
                    }
                }
            }

            WorkflowActivityDto result = new WorkflowActivityDto();

            databaseContext.Commit();
            return result;
        }

        /// <summary>
        /// 通过节点
        /// </summary>
        private WorkflowActivityStepEntity PassNode(WorkflowActivityStepEntity activityStepEntity)
        {
            activityStepEntity.CompleteType = OAActivityStepCompleteType.Pass;
            return this.workflowActivityStepData.UpdateStepStatusToComplete(activityStepEntity).GetAwaiter().GetResult();
        }
        /// <summary>
        /// 驳回节点
        /// </summary>
        private WorkflowActivityStepEntity RejectNode(WorkflowActivityStepEntity activityStepEntity)
        {
            activityStepEntity.CompleteType = OAActivityStepCompleteType.Reject;
            return this.workflowActivityStepData.UpdateStepStatusToComplete(activityStepEntity).GetAwaiter().GetResult();
        }
        /// <summary>
        /// 修改步骤按钮显示条件
        /// </summary>
        private WorkflowActivityStepEntity UpdateStepButtonShowCondition(WorkflowActivityStepEntity activityStepEntity)
        {
            return this.workflowActivityStepData.UpdateStepButtonShowCondition(activityStepEntity).GetAwaiter().GetResult();
        }

        /// <summary>
        /// 检查当前步骤操作
        /// </summary>
        private void CheckCurrentlyStepOpertionComplete(WorkflowActivityStepEntity activityStepEntity)
        {
            var list = this.workflowActivityStepCompleteCheckingData.GetList(activityStepEntity.WorkflowActivityStepId).GetAwaiter().GetResult();
            if (list.Any(p => p.AllowIgnore == false && p.OpertionStatus == OAActivityStepOpertionStatus.Pending))
            {
                var error = list.Where(p => p.AllowIgnore == false && p.OpertionStatus == OAActivityStepOpertionStatus.Pending);
                throw new ArgumentException(string.Format("步骤操作检查失败，请完成步骤中 {0} 的操作。", string.Join('、', error.Select(p => "【" + p.OpertionName + "】"))));
            }
        }
        #region 设置上一步或下一步节点信息
        private void GetTargetStepInfo(WorkflowActivityStepEntity activityStepEntity, bool isPass)
        {
            var activityStepList = this.workflowActivityStepData.GetList(activityStepEntity.WorkflowCode).GetAwaiter().GetResult();
            var templateStepList = this.workflowTemplateStepData.GetList(activityStepEntity.TemplateCode).GetAwaiter().GetResult();
            var stepLineList = this.workflowTemplateStepLineConfigData.GetList(activityStepEntity.TemplateCode).GetAwaiter().GetResult();
            if (isPass)
            {
                var nextStepLines = stepLineList.Where(p => p.TemplateStepCode == activityStepEntity.TemplateStepCode && p.PathType == OAStepPathType.Pass && p.StartId == activityStepEntity.TemplateStepCode);
                foreach (var nextStepLine in nextStepLines)
                {
                    //var nextStepEntity = activityStepList.Single(p => p.TemplateStepCode == nextStepLine.EndId);
                    var templateStepEntity = templateStepList.Single(p => p.Id == nextStepLine.EndId);
                    var stepBaseCofnigEntity = this.workflowTemplateStepBaseConfigData.GetEntity(nextStepLine.EndId).GetAwaiter().GetResult();
                    if (stepBaseCofnigEntity != null)
                    {
                        SetNextNode(templateStepEntity, activityStepEntity, OAActivityStepType.Created, stepBaseCofnigEntity.AllowAdditionalValidationPerson);
                    }
                    else
                    {
                        SetNextNode(templateStepEntity, activityStepEntity, OAActivityStepType.Created, false);
                    }
                }
            }
            else
            {
                var rejectStepLine = stepLineList.FirstOrDefault(p => p.TemplateStepCode == activityStepEntity.TemplateStepCode && p.PathType == OAStepPathType.Reject && p.StartId == activityStepEntity.TemplateStepCode);
                var nextStepEntity = activityStepList.Single(p => p.TemplateStepCode == rejectStepLine.TemplateStepCode);
                SetRejectNode(nextStepEntity, null, true);
            }
        }

        /// <summary>
        /// 设置驳回到上一步骤节点信息
        /// </summary>
        /// <param name="activityStepEntity">当前步骤节点信息</param>
        /// <param name="rejectRemark">驳回备注</param>
        /// <param name="plusStep">是增加工作流步骤号</param>
        private void SetRejectNode(WorkflowActivityStepEntity activityStepEntity, string rejectRemark, bool plusStep)
        {
            var activityStepList = this.workflowActivityStepData.GetList(activityStepEntity.WorkflowCode).GetAwaiter().GetResult();
            int preStep = plusStep ? activityStepEntity.Step + 1 : activityStepEntity.Step - 1;
            var preStepEntity = activityStepList.First(p => p.Step == preStep);

            WorkflowActivityStepEntity nextStepEntity = preStepEntity;
            nextStepEntity.TemplateCode = preStepEntity.TemplateCode;
            nextStepEntity.TemplateName = preStepEntity.TemplateName;
            nextStepEntity.WorkflowCode = preStepEntity.WorkflowCode;
            nextStepEntity.WorkflowName = preStepEntity.WorkflowName;
            nextStepEntity.TemplateStepCode = preStepEntity.TemplateStepCode;
            nextStepEntity.StepCode = Guid.NewGuid().ToString();
            nextStepEntity.NodeName = activityStepEntity.NodeName;
            nextStepEntity.NodeType = OAStepNodeType.Node;
            nextStepEntity.StepType = OAActivityStepType.Created;
            nextStepEntity.StepStatus = OAActivityStepStatus.Pending;
            nextStepEntity.StepOrder = activityStepEntity.StepOrder + 1;
            nextStepEntity.IsAdditionalValidationStep = true;
            nextStepEntity.AllowAssignNextValidater = false;
            nextStepEntity.RejectedRemark = rejectRemark;
            nextStepEntity.WorkflowActivityId = activityStepEntity.WorkflowActivityId;
            SaveNextNode(nextStepEntity, false);
        }

        /// <summary>
        /// 设置下一节点信息（附加步骤）
        /// </summary>
        /// <param name="activityStepEntity">下一节点步骤信息</param>
        /// <param name="nextAuditorId">下一节点执行人</param>
        /// <param name="additionalRemark">加签备注</param>
        private void SetNextNode(WorkflowActivityStepEntity activityStepEntity, long nextAuditorId, string additionalRemark)
        {
            WorkflowActivityStepEntity nextStepEntity = activityStepEntity;
            nextStepEntity.TemplateCode = activityStepEntity.TemplateCode;
            nextStepEntity.TemplateName = activityStepEntity.TemplateName;
            nextStepEntity.WorkflowCode = activityStepEntity.WorkflowCode;
            nextStepEntity.WorkflowName = activityStepEntity.WorkflowName;
            nextStepEntity.WorkflowActivityId = activityStepEntity.WorkflowActivityId;
            nextStepEntity.TemplateStepCode = activityStepEntity.TemplateStepCode;
            nextStepEntity.StepCode = Guid.NewGuid().ToString();
            nextStepEntity.CompleteType = null;
            nextStepEntity.NodeName = activityStepEntity.NodeName;
            nextStepEntity.NodeType = OAStepNodeType.Node;
            nextStepEntity.StepType = OAActivityStepType.Created;
            nextStepEntity.StepStatus = OAActivityStepStatus.Pending;
            nextStepEntity.StepOrder = activityStepEntity.StepOrder + 1;
            nextStepEntity.IsAdditionalValidationStep = true;
            nextStepEntity.AllowAssignNextValidater = true;
            nextStepEntity.AdditionalRemark = additionalRemark;
            var stepEntityResult = SaveNextNode(nextStepEntity, true);

            var workflowActivityEntity = this.workflowActivityData.GetEntity(stepEntityResult.WorkflowActivityId).GetAwaiter().GetResult();
            WorkflowActivityStepReviewerEntity reviewerEntity = new WorkflowActivityStepReviewerEntity();
            reviewerEntity.WorkflowCategoryId = workflowActivityEntity.WorkflowCategoryId;
            reviewerEntity.WorkflowActivityId = stepEntityResult.WorkflowActivityId;
            reviewerEntity.WorkflowActivityStepId = stepEntityResult.WorkflowActivityStepId;
            reviewerEntity.CategoryCode = workflowActivityEntity.CategoryCode;
            reviewerEntity.CategoryName = workflowActivityEntity.CategoryName;
            reviewerEntity.TemplateCode = stepEntityResult.TemplateCode;
            reviewerEntity.TemplateName = stepEntityResult.TemplateName;
            reviewerEntity.WorkflowCode = stepEntityResult.WorkflowCode;
            reviewerEntity.WorkflowName = stepEntityResult.WorkflowName;
            reviewerEntity.TemplateStepCode = stepEntityResult.TemplateStepCode;
            reviewerEntity.StepCode = stepEntityResult.StepCode;
            reviewerEntity.NotificationTitle = string.Format("您好，您有一个新任务【{0}】请及时处理！", stepEntityResult.TemplateName);
            reviewerEntity.AdminId = nextAuditorId;
            var stepPreviewerResult = this.workflowActivityStepReviewerData.Add(reviewerEntity).GetAwaiter().GetResult();
            if (stepPreviewerResult == null)
            {
                throw new ArgumentException("设置下一节点审核人信息失败!");
            }
            List<WorkflowActivityStepReviewerEntity> reviewerEntities = new List<WorkflowActivityStepReviewerEntity>();
            reviewerEntities.Add(stepPreviewerResult);
            NotificationNextNodePreviewer(stepEntityResult, reviewerEntities);
            nextStepEntity.ActiveTime = DateTime.Now;
            nextStepEntity.StepStatus = OAActivityStepStatus.Active;
            var adminEntity = this.adminData.GetAdmin(nextAuditorId).GetAwaiter().GetResult();
            if (adminEntity == null)
            {
                throw new ArgumentException("设置步骤执行人时，获取员工信息失败!");
            }
            nextStepEntity.ExecutorId = adminEntity.AdminId;
            nextStepEntity.ExecutorName = adminEntity.FullName;
            nextStepEntity.ExecutorType = OAAuthorRoleType.Admin;
            var result = this.workflowActivityStepData.UpdateStepStatusToActivity(nextStepEntity).GetAwaiter().GetResult().As<WorkflowActivityStepDto>();
            if (result == null)
            {
                throw new ArgumentException("激活工作流活动步骤时失败!");
            }
        }
        /// <summary>
        /// 设置下一节点信息（非附加步骤）
        /// </summary>
        /// <param name="templateStepEntity">工作流步骤模板信息</param>
        /// <param name="activityStepEntity">工作流当前操作步骤信息</param>
        /// <param name="activityStepType">工作流下一步骤构建类型</param>
        /// <param name="allowAssignNextValidater">是否允许指定下一步骤审核人</param>
        private void SetNextNode(WorkflowTemplateStepEntity templateStepEntity, WorkflowActivityStepEntity activityStepEntity, OAActivityStepType activityStepType, bool allowAssignNextValidater)
        {
            WorkflowActivityStepEntity nextStepEntity = new WorkflowActivityStepEntity();
            nextStepEntity.TemplateCode = templateStepEntity.TemplateCode;
            nextStepEntity.TemplateName = templateStepEntity.TemplateName;
            nextStepEntity.WorkflowCode = activityStepEntity.WorkflowCode;
            nextStepEntity.WorkflowName = activityStepEntity.WorkflowName;
            nextStepEntity.WorkflowActivityId = activityStepEntity.WorkflowActivityId;
            nextStepEntity.TemplateStepCode = templateStepEntity.Id;
            nextStepEntity.StepCode = Guid.NewGuid().ToString();
            nextStepEntity.NodeName = templateStepEntity.NodeName;
            nextStepEntity.NodeType = templateStepEntity.NodeType;
            nextStepEntity.StepType = activityStepType;
            nextStepEntity.Step = templateStepEntity.Step;
            nextStepEntity.StepStatus = OAActivityStepStatus.Pending;
            nextStepEntity.StepOrder = activityStepEntity.StepOrder + 1;
            nextStepEntity.IsAdditionalValidationStep = false;
            nextStepEntity.AllowAssignNextValidater = allowAssignNextValidater;
            WorkflowActivityStepEntity stepNodeEntity = SaveNextNode(nextStepEntity, false);
            SetNextNodePreviewer(stepNodeEntity);
        }
        /// <summary>
        /// 保存下一节点
        /// </summary>
        /// <param name="nextStepEntity">下一步节点信息</param>
        /// <param name="isAdditionalValidationStep">是否为加签步骤</param>
        private WorkflowActivityStepEntity SaveNextNode(WorkflowActivityStepEntity nextStepEntity, bool isAdditionalValidationStep)
        {

            var stepEntityResult = this.workflowActivityStepData.Add(nextStepEntity).GetAwaiter().GetResult();

            if (stepEntityResult == null)
            {
                throw new ArgumentException("初始化工作流活动步骤失败!");
            }
            if (!isAdditionalValidationStep)
            {
                List<WorkflowActivityStepCompleteCheckingEntity> completeCheckingEntities = GetStepCompleteCheckingList(nextStepEntity.TemplateStepCode, nextStepEntity);
                if (completeCheckingEntities.Any())
                {
                    foreach (var item in completeCheckingEntities)
                    {
                        item.WorkflowActivityId = nextStepEntity.WorkflowActivityId;
                        item.WorkflowActivityStepId = stepEntityResult.WorkflowActivityStepId;
                        item.CreateTime = DateTime.Now;
                        item.OpertionStatus = OAActivityStepOpertionStatus.Pending;
                    }

                    if (!this.workflowActivityStepCompleteCheckingData.Add(completeCheckingEntities).GetAwaiter().GetResult())
                    {
                        throw new ArgumentException("构建工作流步骤操作检查列表失败!");
                    }
                }
            }
            return stepEntityResult;
        }
        #endregion

        /// <summary>
        /// 设置下一节点审核人
        /// </summary>
        private void SetNextNodePreviewer(WorkflowActivityStepEntity stepEntity)
        {
            var workflowActivityEntity = this.workflowActivityData.GetEntity(stepEntity.WorkflowActivityId).GetAwaiter().GetResult();

            var list = this.workflowTemplateStepReviewerConfigData.GetListByTemplateStepCode(stepEntity.TemplateStepCode).GetAwaiter().GetResult();
            List<WorkflowActivityStepReviewerEntity> reviewerEntities = new List<WorkflowActivityStepReviewerEntity>();
            foreach (var item in list)
            {
                WorkflowActivityStepReviewerEntity reviewerEntity = new WorkflowActivityStepReviewerEntity();
                reviewerEntity.WorkflowCategoryId = workflowActivityEntity.WorkflowCategoryId;
                reviewerEntity.WorkflowActivityId = stepEntity.WorkflowActivityId;
                reviewerEntity.WorkflowActivityStepId = stepEntity.WorkflowActivityStepId;
                reviewerEntity.CategoryCode = workflowActivityEntity.CategoryCode;
                reviewerEntity.CategoryName = workflowActivityEntity.CategoryName;
                reviewerEntity.TemplateCode = stepEntity.TemplateCode;
                reviewerEntity.TemplateName = stepEntity.TemplateName;
                reviewerEntity.WorkflowCode = stepEntity.WorkflowCode;
                reviewerEntity.WorkflowName = stepEntity.WorkflowName;
                reviewerEntity.TemplateStepCode = stepEntity.TemplateStepCode;
                reviewerEntity.StepCode = stepEntity.StepCode;
                reviewerEntity.CreateTime = DateTime.Now;
                reviewerEntity.NotificationTitle = string.Format("您好，您有一个新任务【{0}】请及时处理！", stepEntity.TemplateName);
                switch (item.PermissionType)
                {
                    case "Company":
                        {
                            if (!int.TryParse(item.PermissionReferenceId, out int companyId))
                            {
                                throw new ArgumentException("指定审核人时异常，指定信息【公司信息】设置错误!");
                            }
                            var assignPreviewerEntity = this.workflowActivityStepReviewerData.GetWorkMinimumReviewerByCompanyId(companyId).GetAwaiter().GetResult();
                            reviewerEntity.CompanyId = companyId;
                            reviewerEntity.DepartmentId = assignPreviewerEntity.DepartmentId;
                            reviewerEntity.AdminId = assignPreviewerEntity.AdminId;
                            reviewerEntities.Add(reviewerEntity);
                        }
                        break;
                    case "Department":
                        {
                            if (!int.TryParse(item.PermissionReferenceId, out int departmentId))
                            {
                                throw new ArgumentException("指定审核人时异常，指定信息【部门信息】设置错误!");
                            }
                            var assignPreviewerEntity = this.workflowActivityStepReviewerData.GetWorkMinimumReviewerByDepartmentId(departmentId).GetAwaiter().GetResult();
                            if (assignPreviewerEntity == null)
                            {
                                throw new ArgumentException("指定审核人时异常，当前指定人不存在，或已离职!");
                            }
                            reviewerEntity.CompanyId = assignPreviewerEntity.CompanyId;
                            reviewerEntity.DepartmentId = departmentId;
                            reviewerEntity.AdminId = assignPreviewerEntity.AdminId;
                            reviewerEntities.Add(reviewerEntity);
                        }
                        break;
                    case "Human":
                        {
                            if (!long.TryParse(item.PermissionReferenceId, out long adminId))
                            {
                                throw new ArgumentException("指定审核人时异常，指定信息【部门信息】设置错误!");
                            }
                            var staffOrganizationMappingRecordEntity = this.staffOrganizationMappingRecordData.GetActiveEntity(adminId).GetAwaiter().GetResult();
                            reviewerEntity.AdminId = adminId;
                            if (staffOrganizationMappingRecordEntity == null)
                            {
                                throw new ArgumentException("指定审核人时异常，当前指定人不存在，或已离职!");
                            }
                            reviewerEntity.CompanyId = staffOrganizationMappingRecordEntity.CompanyId;
                            reviewerEntity.DepartmentId = staffOrganizationMappingRecordEntity.DepartmentId;
                            reviewerEntities.Add(reviewerEntity);
                        }
                        break;
                    case "Position":
                        {
                            if (!int.TryParse(item.PermissionReferenceId, out int positionId))
                            {
                                throw new ArgumentException("指定审核人时异常，指定信息【岗位信息】设置错误!");
                            }
                            var positionEntity = this.positionData.GetEntity(positionId).GetAwaiter().GetResult();
                            var staffList = this.staffOrganizationMappingRecordData.GetPositionStaffList(positionEntity.PositionNo).GetAwaiter().GetResult();
                            if (!staffList.Any())
                            {
                                throw new ArgumentException("指定审核人时异常，当前指定人不存在，或已离职!");
                            }
                            foreach (var staff in staffList)
                            {
                                WorkflowActivityStepReviewerEntity activityStepReviewerEntity = reviewerEntity;
                                activityStepReviewerEntity.AdminId = staff.AdminId;
                                activityStepReviewerEntity.CompanyId = staff.CompanyId;
                                activityStepReviewerEntity.DepartmentId = staff.DepartmentId;
                                reviewerEntities.Add(activityStepReviewerEntity);
                            }
                        }
                        break;
                    case "NodePerson":
                        {
                            var stepList = this.workflowActivityStepData.GetList(workflowActivityEntity.WorkflowCode).GetAwaiter().GetResult();
                            if (!stepList.Any(p => p.StepCode == item.PermissionReferenceId))
                            {
                                throw new ArgumentException("指定审核人时异常，指定信息【节点执行人信息】设置错误!此步骤节点不存在!");
                            }
                            var step = stepList.First(p => p.StepCode == item.PermissionReferenceId);
                            var assignPreviewerEntity = this.workflowActivityStepReviewerData.GetEntityByStepId(step.WorkflowActivityStepId).GetAwaiter().GetResult();
                            if (assignPreviewerEntity == null)
                            {
                                throw new ArgumentException("指定审核人时异常，当前指定人不存在，或已离职!");
                            }
                            reviewerEntity.AdminId = assignPreviewerEntity.AdminId;
                            reviewerEntity.CompanyId = assignPreviewerEntity.CompanyId;
                            reviewerEntity.DepartmentId = assignPreviewerEntity.DepartmentId;
                            reviewerEntities.Add(reviewerEntity);
                        }
                        break;
                    default:
                        {
                            if (!int.TryParse(item.PermissionReferenceId, out int userId))
                            {
                                throw new ArgumentException("指定审核人时异常，指定信息【其他人员信息】设置错误!");
                            }
                            reviewerEntity.OtherUserId = userId;
                            reviewerEntities.Add(reviewerEntity);
                        }
                        break;
                }
            }
            if (reviewerEntities.Any())
            {
                if (!this.workflowActivityStepReviewerData.Add(reviewerEntities).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("设置下一节点审核人信息失败!");
                }
                NotificationNextNodePreviewer(stepEntity, reviewerEntities);
            }
            stepEntity.ActiveTime = DateTime.Now;
            stepEntity.StepStatus = OAActivityStepStatus.Active;
            var result = this.workflowActivityStepData.UpdateStepStatusToActivity(stepEntity).GetAwaiter().GetResult().As<WorkflowActivityStepDto>();
            if (result == null)
            {
                throw new ArgumentException("激活工作流活动步骤时失败!");
            }
            if (stepEntity.NodeType == OAStepNodeType.End)
            {
                stepEntity.CompleteTime = DateTime.Now;
                stepEntity.StepStatus = OAActivityStepStatus.Done;
                stepEntity.CompleteType = OAActivityStepCompleteType.Pass;
                result = this.workflowActivityStepData.UpdateStepStatusToComplete(stepEntity).GetAwaiter().GetResult().As<WorkflowActivityStepDto>();
                if (result == null)
                {
                    throw new ArgumentException("完成工作流活动步骤时失败!");
                }
            }
        }
        /// <summary>
        /// 通知下一节点
        /// </summary>
        private void NotificationNextNodePreviewer(WorkflowActivityStepEntity stepEntity, List<WorkflowActivityStepReviewerEntity> entities)
        {

        }

        #region 获取步骤完成检查列表
        /// <summary>
        /// 获取步骤完成检查列表
        /// </summary>
        /// <param name="templateStepCode">模板步骤Code</param>
        /// <param name="stepEntity">工作流活动步骤</param>
        /// <returns></returns>
        private List<WorkflowActivityStepCompleteCheckingEntity> GetStepCompleteCheckingList(string templateStepCode, WorkflowActivityStepEntity stepEntity)
        {
            #region 设置工作流步骤完成检查列表
            List<WorkflowActivityStepCompleteCheckingEntity> completeCheckingEntities = new List<WorkflowActivityStepCompleteCheckingEntity>();

            var templateStepFormList = this.workflowTemplateStepFormTemplateConfigData.GetStepFormList(templateStepCode).GetAwaiter().GetResult();
            if (templateStepFormList.Any())
            {
                foreach (var item in templateStepFormList)
                {
                    WorkflowActivityStepCompleteCheckingEntity completeCheckingEntity = new WorkflowActivityStepCompleteCheckingEntity();
                    completeCheckingEntity.TemplateCode = stepEntity.TemplateCode;
                    completeCheckingEntity.TemplateName = stepEntity.TemplateName;
                    completeCheckingEntity.WorkflowCode = stepEntity.WorkflowCode;
                    completeCheckingEntity.WorkflowName = stepEntity.WorkflowName;
                    completeCheckingEntity.TemplateStepCode = stepEntity.TemplateStepCode;
                    completeCheckingEntity.StepCode = stepEntity.StepCode;
                    completeCheckingEntity.StepOrder = stepEntity.StepOrder;
                    completeCheckingEntity.FormConfigCode = item.FormConfigCode;
                    completeCheckingEntity.OpertionName = item.FormConfigTitle;
                    completeCheckingEntity.OpertionType = OAActivityStepOperationDescription.SubmitForm.ToString();
                    completeCheckingEntity.OpertionStatus = OAActivityStepOpertionStatus.Pending;
                    completeCheckingEntity.AllowIgnore = false;
                    completeCheckingEntities.Add(completeCheckingEntity);
                }
            }

            if (stepEntity.AllowAssignNextValidater)
            {
                WorkflowActivityStepCompleteCheckingEntity completeCheckingEntity = new WorkflowActivityStepCompleteCheckingEntity();
                completeCheckingEntity.TemplateCode = stepEntity.TemplateCode;
                completeCheckingEntity.TemplateName = stepEntity.TemplateName;
                completeCheckingEntity.WorkflowCode = stepEntity.WorkflowCode;
                completeCheckingEntity.WorkflowName = stepEntity.WorkflowName;
                completeCheckingEntity.TemplateStepCode = stepEntity.TemplateStepCode;
                completeCheckingEntity.StepCode = stepEntity.StepCode;
                completeCheckingEntity.StepOrder = stepEntity.StepOrder;
                completeCheckingEntity.OpertionName = OAActivityStepOperationDescription.NextAuditor.GetDescriptionString();
                completeCheckingEntity.OpertionType = OAActivityStepOperationDescription.NextAuditor.ToString();
                completeCheckingEntity.OpertionStatus = OAActivityStepOpertionStatus.Pending;
                completeCheckingEntity.AllowIgnore = true;
                completeCheckingEntities.Add(completeCheckingEntity);
            }
            return completeCheckingEntities;
            #endregion
        }
        #endregion

        #endregion

        #region 修改工作流步骤状态为已激活
        public WorkflowActivityStepDto UpdateStepStatusToActivity(WorkflowActivityStepPutDto putDto, AdminDto adminDto, UserDto userDto)
        {
            if (!this.workflowActivityStepData.Exists(putDto.WorkflowActivityStepId).GetAwaiter().GetResult())
            {
                throw new ArgumentException("此记录不存在!");
            }

            var stepEntity = this.workflowActivityStepData.GetEntity(putDto.WorkflowActivityStepId).GetAwaiter().GetResult();
            if (stepEntity.ActiveTime.HasValue)
            {
                return stepEntity.As<WorkflowActivityStepDto>();
            }

            var entity = putDto.As<WorkflowActivityStepEntity>();
            entity.ActiveTime = DateTime.Now;
            entity.StepStatus = OAActivityStepStatus.Active;
            if (adminDto != null)
            {
                entity.ExecutorId = adminDto.AdminId;
                entity.ExecutorName = adminDto.FullName;
                entity.ExecutorType = OAAuthorRoleType.Admin;
            }
            else
            {
                entity.ExecutorId = userDto.UserId;
                entity.ExecutorName = userDto.UserName;
                entity.ExecutorType = OAAuthorRoleType.Other;
            }
            var result = this.workflowActivityStepData.UpdateStepStatusToActivity(entity).GetAwaiter().GetResult().As<WorkflowActivityStepDto>();
            return result;
        }
        #endregion

        #region 修改工作流步骤状态为已完成
        public WorkflowActivityStepDto UpdateStepStatusToComplete(WorkflowActivityStepPutDto putDto)
        {
            if (!this.workflowActivityStepData.Exists(putDto.WorkflowActivityStepId).GetAwaiter().GetResult())
            {
                throw new ArgumentException("此记录不存在!");
            }
            var entity = putDto.As<WorkflowActivityStepEntity>();
            entity.CompleteTime = DateTime.Now;
            entity.StepStatus = OAActivityStepStatus.Done;
            var result = this.workflowActivityStepData.UpdateStepStatusToComplete(entity).GetAwaiter().GetResult().As<WorkflowActivityStepDto>();
            return result;
        }
        #endregion

        #region 获取工作流活动信息
        public WorkflowActivityDto GetEntity(long workflowActivityId)
        {
            return this.workflowActivityData.GetEntity(workflowActivityId).GetAwaiter().GetResult().As<WorkflowActivityDto>();
        }
        #endregion

        #region 获取工作流活动步骤列表
        public IEnumerable<WorkflowActivityStepDto> GetActivityStepList(long workflowActivityId)
        {
            return this.workflowActivityStepData.GetList(workflowActivityId).GetAwaiter().GetResult().As<IEnumerable<WorkflowActivityStepDto>>();
        }
        #endregion

        #region 获取工作流活动分页列表(待处理任务)
        public PageableList<WorkflowActivityViewDto> PendingHandleTaskQuery(long adminId, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            var data = this.workflowActivityData.PendingHandleTaskQuery(adminId, start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
            var result = new PageableList<WorkflowActivityViewDto>()
            {
                Count = data.Item2,
                Items = data.Item1.As<IEnumerable<WorkflowActivityViewDto>>(),
                ServerTime = DateTime.Now,
                PageIndex = pageIndex,
                PageSize = pageSize
            };
            return result;
        }
        #endregion

        #region 获取工作流活动分页列表（我发起的，已完成的，已关闭的）
        public PageableList<WorkflowActivityDto> Query(long? adminId, long? userId, OAActivityStatus? activityStatus, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            var data = this.workflowActivityData.Query(adminId, userId, activityStatus, start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
            var result = new PageableList<WorkflowActivityDto>()
            {
                Count = data.Item2,
                Items = data.Item1.As<IEnumerable<WorkflowActivityDto>>(),
                ServerTime = DateTime.Now,
                PageIndex = pageIndex,
                PageSize = pageSize
            };
            return result;
        }
        #endregion

        #region 获取工作流活动步骤表单列表
        public IEnumerable<WorkflowActivityStepFormConfigDto> GetActivityStepFormConfigList(long workflowActivityId)
        {
            var formConfigDtos = this.workflowActivityStepFormConfigData.GetList(workflowActivityId).GetAwaiter().GetResult().As<IEnumerable<WorkflowActivityStepFormConfigDto>>();
            var formItemDtos = this.workflowActivityStepFormItemData.GetList(workflowActivityId).GetAwaiter().GetResult().As<IEnumerable<WorkflowActivityStepFormItemDto>>();
            var specificFormItemDtos = this.workflowActivityStepSpecificFormItemData.GetList(workflowActivityId).GetAwaiter().GetResult().As<IEnumerable<WorkflowActivityStepSpecificFormItemDto>>();
            foreach (var item in formConfigDtos)
            {
                item.FormItemActivity = formItemDtos.Where(p => p.FormConfigCode == item.FormConfigCode).ToList();
            }
            foreach (var item in formConfigDtos)
            {
                var list = specificFormItemDtos.Where(p => p.FormConfigCode == item.FormConfigCode);
                item.SpecificFormItemActivity = list.ToList();
            }
            return formConfigDtos;
        }
        #endregion

        #region 获取工作流活动步骤按钮列表
        public IEnumerable<WorkflowTemplateStepButtonConfigDto> GetActivityStepButtonList(string templateStepCode)
        {
            return this.workflowTemplateStepButtonConfigData.GetStepList(templateStepCode).GetAwaiter().GetResult().As<IEnumerable<WorkflowTemplateStepButtonConfigDto>>();
        }
        #endregion

        #region 修改工作流活动步骤按钮显示条件
        public WorkflowActivityStepDto UpdateStepButtonShowCondition(WorkflowActivityStepButtonConditionPutDto putDto)
        {
            var entity = putDto.As<WorkflowActivityStepEntity>();
            return this.workflowActivityStepData.UpdateStepButtonShowCondition(entity).GetAwaiter().GetResult().As<WorkflowActivityStepDto>();
        }
        #endregion


        #region 获取工作流步骤为条件步骤的活动中列表
        public IEnumerable<WorkflowActivityStepDto> GetWorkflowStepConditionStatusActiveList()
        {
            return this.workflowActivityStepData.GetWorkflowStepConditionStatusActiveList().GetAwaiter().GetResult().As<IEnumerable<WorkflowActivityStepDto>>();
        }
        #endregion

        #region 获取工作流特殊表单已审批完成待处理实例
        public IDictionary<long, string> GetWorkflowActivityStepSpecificFormDone()
        {
            return this.workflowActivityStepData.GetWorkflowActivityStepSpecificFormDone().Result;
        }
        #endregion

        #region 获取工作流活动步骤特殊表单项
        public IEnumerable<WorkflowActivityStepSpecificFormItemDto> GetActivityStepSpecificFormItemList(long workflowActivityId)
        {
            return this.workflowActivityStepSpecificFormItemData.GetList(workflowActivityId).Result.As<IEnumerable<WorkflowActivityStepSpecificFormItemDto>>();
        }
        #endregion

        #region 修改工作流状态为已完成
        public WorkflowActivityDto UpdateActivityStatusToDone(long workflowActivityId)
        {
            var activityEntity = this.workflowActivityData.GetEntity(workflowActivityId).GetAwaiter().GetResult();
            if (activityEntity == null)
            {
                throw new ArgumentException("工作流活动不存在!");
            }
            activityEntity.CompleteTime = DateTime.Now;
            activityEntity.ActivityStatus = OAActivityStatus.Done;
            var result = this.workflowActivityData.Update(activityEntity).GetAwaiter().GetResult();
            return result.As<WorkflowActivityDto>();
        }
        #endregion

        #region 特殊表单数据写入对应表
        public long InsertSpecificFormTable(string tableName, Dictionary<string, string> keyValuePairs)
        {
            return this.workflowActivityStepSpecificFormItemData.InsertSpecificFormTable(tableName, keyValuePairs).GetAwaiter().GetResult();
        }
        #endregion

        #region 更新特殊表单数据处理已执行
        public void UpdateSpecificFormIsExecution(long workflowActivityId, string tableName, int? formConfigRows, int? formItemRows)
        {
            this.workflowActivityStepSpecificFormItemData.UpdateSpecificFormIsExecution(workflowActivityId, tableName, formConfigRows, formItemRows).GetAwaiter().GetResult();
        }
        #endregion

        #region 特殊表单数据更新对应表
        public void UpdateSpecificFormTable(string tableName, Dictionary<string, string> keyValuePairs, Dictionary<string, string> updateKeyValuePairs)
        {
            this.workflowActivityStepSpecificFormItemData.UpdateSpecificFormTable(tableName, keyValuePairs, updateKeyValuePairs).GetAwaiter().GetResult();
        }
        #endregion
    }
}
